package com.mh.server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author MH
 * @since 2021-10-26
 */
public class Bootstrap {

    private final int port;

    public Bootstrap(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        loadServlet();
        ServerSocket serverSocket = new ServerSocket(this.port);
        System.out.println("Minicat 已启动");
        while (true) {
            Socket socket = serverSocket.accept();
            Request request = new Request(socket.getInputStream());
            Response response = new Response(socket.getOutputStream());
            HttpServlet httpServlet = servletMap.get(request.getUrl());
            if (httpServlet == null) {
                response.outputStaticResource(request.getUrl());
            } else {
                httpServlet.service(request, response);
            }
            socket.close();
        }
    }

    private Map<String, HttpServlet> servletMap;

    private void loadServlet() throws DocumentException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        InputStream inputStream = Bootstrap.class.getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(inputStream);
        Element rootElement = document.getRootElement();
        List list = rootElement.selectNodes("/web-app/servlet");
        this.servletMap = new HashMap<>(list.size() * 3 / 4 + 1);
        for (Object obj : list) {
            Element servlet = (Element) obj;
            String servletName = servlet.selectSingleNode("servlet-name").getStringValue();
            String servletClass = servlet.selectSingleNode("servlet-class").getStringValue();
            Node node = rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
            String urlPattern = node.selectSingleNode("url-pattern").getStringValue();
            this.servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
        }
    }

    public static void main(String[] args) throws Exception {
        Bootstrap bootstrap = new Bootstrap(8080);
        bootstrap.start();
    }
}
